package api

import (
	"api-server/basic/config"
	"api-server/handler/model"
	"api-server/handler/request"
	__ "api-server/proto"
	"api-server/until"
	"context"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

func Register(c *gin.Context) {
	var req request.RegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"date": err.Error(),
		})
		return
	}
	_, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	_, err := config.ShopClient.Register(c, &__.RegisterReq{
		Mobile:   req.Mobile,
		Password: req.Password,
	})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	//err = config.Rdb.Get(config.Rdb.Context(), "register").Err()
	//if err != nil {
	//	panic()
	//}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"date": nil,
	})
}

func Login(c *gin.Context) {
	var req request.RegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"date": err.Error(),
		})
		return
	}
	_, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	_, err := config.ShopClient.Register(c, &__.RegisterReq{
		Mobile:   req.Mobile,
		Password: req.Password,
	})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	token, _ := until.NewJWT("2210a").CreateToken(until.CustomClaims{ID: uint(req.Id)})
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"date": token,
	})
}
func List(c *gin.Context) {
	var req request.ListReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"date": err.Error(),
		})
		return
	}
	_, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	_, err := config.ShopClient.List(c, &__.ListOrderReq{
		Page:     int64(req.Page),
		SizePage: int64(req.PageSize),
	})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	var shop model.Shop
	list := config.DB.First(&shop)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"date": list,
	})
}
